<?php
namespace  app\appapi;

class WeShare
{
    private $cert_pem;//证书
    private $key_pem;//密钥
        /**
     * 页内调起支付
     * 商户生成订单，先调用统一支付接口获取到 code_url，
     * H5调起支付
     */
    public function getPayJsApi($wtconfig,$body,$out_trade_no,$total_fee,$openid,$attach = ''){
        $arr = [
                'appid' =>$wtconfig['app_id'],//微信小程序Appid,此处注意，小程序支付一定要用小程序的APPID，公众号则用公众号的
                'mch_id'=>$wtconfig['mch_id'],//微信公众号mch_id
                'nonce_str'=>$this->createNoncestr(),
                'body'=>$body,
                'out_trade_no'=>$out_trade_no,
                'total_fee'=>$total_fee*100,//单位分
                // 'total_fee'=>1,//测试
                'spbill_create_ip'=>$_SERVER['REMOTE_ADDR'],
				'notify_url'=>$wtconfig['notify_url'],
                'trade_type'=>'JSAPI',
                'openid'=>$openid,
            ];
        if($attach && $attach != '')
        $arr['attach'] = $attach;
        $arr['sign'] = $this->getSign($arr,$wtconfig['key']);
        $data = $this->arrayToXml($arr);
        $url ='https://api.mch.weixin.qq.com/pay/unifiedorder';
        $result = $this->postDataCurl($data,$url);                  
        $array = $this->xmlToArray($result);
		// print_r($array);exit;
        if(!$array || $array['return_code'] != 'SUCCESS' || $array['return_msg'] != 'OK')
        return false;
        $payData = $this->getParameters($array['prepay_id'],$wtconfig['app_id'],$wtconfig['key']);
        return $payData;
    }


     /**
     * 企业付款到零钱
     */
    public function getPayCashWithdrawal($wtconfig,$body,$out_trade_no,$total_fee,$openid,$chars='NO_CHECK'){
        $this->cert_pem = $wtconfig['cert_path'];
        $this->key_pem = $wtconfig['cert_key'];
        $arr = [
                'mch_appid' =>$wtconfig['app_id'],///微信小程序Appid,此处注意，小程序支付一定要用小程序的APPID，公众号则用公众号的
                'mchid'=>$wtconfig['mch_id'],//微信公众号mch_id
                'nonce_str'=>$this->createNoncestr(),
                'desc'=>$body,
                'partner_trade_no'=>$out_trade_no,
                'amount'=>$total_fee*100,//单位分
                // 'amount'=>1*100,//测试
                'spbill_create_ip'=>$_SERVER['REMOTE_ADDR'],
				'check_name'=>$chars,//默认不校检真名'
                //'re_user_name'=>'',//check_name为FORCE_CHECK必填用户真实姓名
                'openid'=>$openid,
            ];
        $arr['sign'] = $this->getSign($arr,$wtconfig['key']);
        $data = $this->arrayToXml($arr);
        $url ='https://api.mch.weixin.qq.com/mmpaymkttransfers/promotion/transfers';
        $result = $this->postDataCurl($data,$url);
        $array = $this->xmlToArray($result);
        // if(!$array || $array['return_code'] != 'SUCCESS' || $array['return_msg'] != 'OK')
        // return false;
        return $array;
    }

     /**
     * 查询企业付款到零钱
     */
     public function judgeCashWithdrawal($wtconfig,$out_trade_no){
        $arr = [
                'mch_appid' =>$wtconfig['app_id'],///微信小程序Appid,此处注意，小程序支付一定要用小程序的APPID，公众号则用公众号的
                'mchid'=>$wtconfig['mch_id'],//微信公众号mch_id
                'nonce_str'=>$this->createNoncestr(),
                'partner_trade_no'=>$out_trade_no,
            ];
        $arr['sign'] = $this->getSign($arr,$wtconfig['key']);
        $data = $this->arrayToXml($arr);
        $url ='https://api.mch.weixin.qq.com/mmpaymkttransfers/promotion/transfers';
        $result = $this->postDataCurl($data,$url);
        $data = $this->xmlToArray($result);
        $payData = $this->getParameters($data['prepay_id'],$wtconfig['app_id'],$wtconfig['key']);
        return $payData;
    }

    /**
     * 	作用：设置jsapi的参数
     */
    public function getParameters($prepay_id,$appid,$key)
    {
        $timeStamp = time();
        $arr = [
            'appId' => $appid,
            'timeStamp'=>"$timeStamp",
            'nonceStr'=>$this->createNoncestr(),
            'package' => "prepay_id=$prepay_id",
            'signType'=>"MD5",
        ];
        $arr['paySign'] = $this->getSign($arr,$key);
        return $arr;
    }


     /*
     * APP支付异步通知
     * */

    public function getNotifyRequestData()
    {
        $xml = file_get_contents("php://input");
        if( empty($xml) ){
            return false;
        }
        $data = $this->xmlToArray($xml);
        return $data;

        // $result_xml = xml_parser_create();
        // xml_parse_into_struct($result_xml, $data, $vals, $index);
        // xml_parser_free($result_xml);
        // foreach( $vals as $k)
        // {
        //     if(strtolower($k['tag'])!='xml')$result_array[strtolower($k['tag'])] = $k['value'];
        // }
    }
    
/**
     * 	作用：array转xml
     */
    function arrayToXml($arr)
    {
        $xml = "<xml>";
        foreach ($arr as $key=>$val)
        {
            if (is_numeric($val))
            {
                $xml.="<".$key.">".$val."</".$key.">";

            }
            else
                $xml.="<".$key."><![CDATA[".$val."]]></".$key.">";
        }
        $xml.="</xml>";
        return $xml;
    }
    /**
     * 	作用：将xml转为array
     */
    public function xmlToArray($xml)
    {
        //将XML转为array
        $array_data = json_decode(json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
        return $array_data;
    }
    /**
     * 	作用：产生随机字符串，不长于32位
     */
    public function createNoncestr( $length = 32 )
    {
        $chars = "abcdefghijklmnopqrstuvwxyz0123456789";
        $str ="";
        for ( $i = 0; $i < $length; $i++ )  {
            $str.= substr($chars, mt_rand(0, strlen($chars)-1), 1);
        }
        return $str;
    }
    /**
     * 	作用：生成签名
     */
    public function getSign($Parameters,$key)
    {
        //签名步骤一：按字典序排序参数
        ksort($Parameters);
        $String = $this->formatBizQueryParaMap($Parameters, false);
        //echo '【string1】'.$String.'</br>';
        //签名步骤二：在string后加入KEY
        $String = $String."&key=".$key;
        //echo "【string2】".$String."</br>";
        //签名步骤三：MD5加密
        $String = md5($String);
        //echo "【string3】 ".$String."</br>";
        //签名步骤四：所有字符转为大写
        $result_ = strtoupper($String);
        //echo "【result】 ".$result_."</br>";
        return $result_;
    }
    /**
     * 	作用：格式化参数，签名过程需要使用
     */
    public function formatBizQueryParaMap($paraMap, $urlencode)
    {
        $buff = "";
        ksort($paraMap);
        foreach ($paraMap as $k => $v)
        {
            if($urlencode)
            {
                $v = urlencode($v);
            }
            //$buff .= strtolower($k) . "=" . $v . "&";
            $buff .= $k . "=" . $v . "&";
        }
        $reqPar='';
        if (strlen($buff) > 0)
        {
            $reqPar = substr($buff, 0, strlen($buff)-1);
        }
        return $reqPar;
    }

        /**
        * post请求用户的信息数据  向微信服务器
        * @param $url   string  请求的地址
        * @param array
        */
    public function postDataCurl($data, $url, $second=30){
        $ch = curl_init();
        $header = "Accept-Charset: utf-8";
        curl_setopt($ch, CURLOPT_TIMEOUT, $second);//设置超时时间
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        // curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
        curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (compatible; MSIE 5.01; Windows NT 5.0)');
        // curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
        curl_setopt($ch, CURLOPT_AUTOREFERER, 1);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_HEADER, FALSE);
        curl_setopt($ch, CURLOPT_POST, TRUE);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        //证书验证
        if($this->cert_pem && $this->key_pem){
            if(!file_exists($this->cert_pem) || !file_exists($this->key_pem))
            return false;
            curl_setopt($ch, CURLOPT_SSLCERT, $this->cert_pem);
            curl_setopt($ch, CURLOPT_SSLKEY, $this->key_pem);
        }
        $tmpInfo = curl_exec($ch);
        //     var_dump($tmpInfo);
        //    exit;
        if (curl_errno($ch)) {
            return false;
        }else{
        // var_dump($tmpInfo);
            return $tmpInfo;
        }
        curl_close($ch);
    }

        /**
        * get请求用户的信息数据  向微信服务器
        * @param $url   string  请求的地址
        * @param array
        */
    public function getDataCurl($url){
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
        curl_setopt($ch, CURLOPT_URL, $url);
        $json =  curl_exec($ch);
        curl_close($ch);
        $arr=json_decode($json,1);
        return $arr;
        //  //设置抓取的url
        // curl_setopt($curl,CURLOPT_URL,$url);
        // curl_setopt($curl,CURLOPT_CONNECTTIMEOUT,30);
        // //设置获取的信息以文件流的形式返回，而不是直接输出。
        // curl_setopt($curl,CURLOPT_RETURNTRANSFER,1);
        // // https请求 不验证证书和hosts
        // curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        // curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
        // //执行命令
        // $response=curl_exec($curl);
        // //关闭URL请求
        // curl_close($curl);
        // //返回数据
        // return $response;
    }

    public function wxNetworkRequest($url,$post_data,$method='POST') {
        $postdata = http_build_query($post_data);
        $options = array(
        'http' => array(
            'method' => $method, //or GET
            'header' => 'Content-type:application/x-www-form-urlencoded',
            'content' => $postdata,
            'timeout' => 15 * 60 // 超时时间（单位:s）
        )
        );
        $context = stream_context_create($options);
        $result = file_get_contents($url, false, $context);
        return $result;
    }
}